package com.changgou.order.controller;

import com.alibaba.fastjson.JSON;
import com.changgou.common.constant.StatusCode;
import com.changgou.common.util.TokenDecode;
import com.changgou.common.vo.Result;
import com.changgou.order.pojo.OrderItem;
import com.changgou.order.service.CartService;
import com.changgou.user.feign.UserFeign;
import com.changgou.user.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/cart")
public class CartController {

    @Autowired
    private CartService cartService;

   @Autowired
   private UserFeign userFeign;


    /**
     * 将商品及购买数量加入到当前登录用户对应的购物车中
     * @param id 商品id sku id
     * @param num 加入购物车数量
     * @return 操作结果
     */
    @GetMapping("/add")
    public Result add(Long id,Integer num){

        try {
            //用户名
            //String username="itheima";
            String username= SecurityContextHolder.getContext().getAuthentication().getName();
            cartService.add(id,num,username);
            return new Result("加入购物车成功！");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return new Result(false, StatusCode.ERROR,"加入购物车失败!");
    }

    /**
     * 查询当前登录用户的购物车列表
     * @return
     */
    @GetMapping("/list")
    public Result<List<OrderItem>> list(){

        try {
            //用户名
            //String username="itheima";
            //方式一：直接从Security中获取
            String username= SecurityContextHolder.getContext().getAuthentication().getName();
            System.out.println("username = " + username);

            //方式二：获取令牌数据
            username= TokenDecode.getUserInfo().get("username");
            System.out.println("解析令牌里面的username = " + username);

            //查询用户
            Result<User> userResult = userFeign.findById(username);
            System.out.println(JSON.toJSONString(userResult));

            List<OrderItem> orderItemList= cartService.list(username);
            return new Result<>("查询购物车成功！", orderItemList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(false, StatusCode.ERROR, "查询购物车失败！");
    }
}
